option explicit
On Error GoTo 0

if Wscript.Arguments.Count <> 1 then
	Err.Raise vbObjectError + 1000, "sitecreate", "Must pass in the name of the site" 
else
    ' msgbox "now"
	call Main( Wscript.Arguments(0) )
end if	

Sub Main(sSiteName)
	Dim g_objSiteCfg
	Dim connStr

	' Create the databases
	Wscript.Echo "Creating for the site"
	connStr = GetDatabaseConnection(sSiteName)
	Wscript.Echo "Site Connection String: " & connStr

	Wscript.Echo "Creating SiteConfig object"
	Set g_objSiteCfg = CreateSiteConfigObject(sSiteName)

	Wscript.Echo "Creating RSS Resource"
	call SetupRssResource(g_objSiteCfg, sSiteName, connStr)

	Wscript.Echo "SiteCreate Completed"

End Sub

Function GetComputerName()
	Dim wshNetwork
	Set WshNetwork = Wscript.CreateObject("Wscript.Network")
	GetComputerName = WshNetwork.ComputerName
End function

Function CreateSiteConfigObject(sSiteName)
    Dim objGrpCfg, objSiteCfg
	Set objGrpCfg = CreateObject("Commerce.GlobalConfig")
	objGrpCfg.Initialize
	Set objSiteCfg = objGrpCfg.CreateSiteConfig(sSiteName)
    objSiteCfg.Initialize sSiteName
    Set objGrpCfg = Nothing
    Set CreateSiteConfigObject = objSiteCfg
end Function


Function GetDatabaseConnection(sSiteName)
	Dim sMasterDSN
	Dim sDBName
	sDBName = sSiteName & "_commerce"
	sMasterDSN = "Provider=SQLOLEDB;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=master;Data Source=" & GetComputerName() & ";"
    Dim objADO
    set objADO = CreateObject("ADODB.Connection")
    objADO.Open sMasterDSN
    On Error Resume Next
    objADO.Execute("Drop Database " & sDBName)
    On Error GoTo 0
    objADO.Execute("Create Database " & sDBName)
    GetDatabaseConnection = "Provider=SQLOLEDB;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=" & sDBName & ";Data Source=" & GetComputerName() & ";"
End Function


Sub SetupRssResource(g_objSiteCfg, sSiteName, connStr)
	const L_sRSSName_Text = "Commerce RSS"
	Dim objRSSPup

	' the below step will fail if you havent imported the definition from RssResourceSchema.sql into
	' the administration database
	g_objSiteCfg.CreateComponentConfig L_sRSSName_Text, "MSCS_RSS"
	g_objSiteCfg.Fields(L_sRSSName_Text).Value.Fields("s_ProgidPUP") = "Commerce.RSSPup"
	g_objSiteCfg.Fields(L_sRSSName_Text).Value.Fields("connstr_db_rss").Value = connStr
	g_objSiteCfg.SaveConfig

	' if you have not set up the RssPup object, the below two steps will fail.
	' to work around this, you can directly execute the rsscreate.sql script 
	' against the RSS database.
	Set objRSSPup = CreateObject("Commerce.RSSPup")
	objRSSPup.Import sSiteName, L_sRSSName_Text, ".", 1
	
End Sub
